const axios = require("axios").default;
const schedule = require("node-schedule");
const moment = require("moment");

const webhook =
  "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5b73d8c0-7f22-44fd-a66e-3d7b7e0fbd95";
const tongzhiwebhook = [webhook];

let isTodayWorkday = true;

/**
 * 获取今天是否是工作日 => 是否需要提醒
 * @returns {Promise<boolean>}
 */
const checkToady = async () => {
  try {
    // 获取指定日期的节假日信息
    const result = (
      await axios.get(
        `https://timor.tech/api/holiday/info/${moment().format("YYYY-MM-DD")}`,
        {
          headers: {
            "User-Agent":
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
          },
        }
      )
    ).data;
    if (result.code === 0) {
      const {
        type: { type },
      } = result;
      isTodayWorkday = type === 0 || type === 3;
      return isTodayWorkday;
    }
    throw new Error(JSON.stringify(result));
  } catch (e) {
    console.error("获取今日是否工作失败了：", e);
    return true;
  }
};

/**
 * 获取下一个休息日提示
 * @returns {Promise<string>}
 */
const getNextHoliday = async () => {
  try {
    const result = (
      await axios.get("http://timor.tech/api/holiday/tts", {
        headers: {
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
        },
      })
    ).data;
    if (result.code === 0) {
      return result.tts;
    }
    throw new Error(result);
  } catch (e) {
    console.error("获取下一个节假日任务失败了：", e);
    return "获取下一个节假日任务失败了。";
  }
};

/**
 *
 * @param {{imageUrl: string, meiriyiju: {title: string, desc: string}}} data 数据
 * @returns
 */
const sendWebhook = (data, webhookUrl) => {
  const params = {
    msgtype: "template_card",
    template_card: {
      card_type: "news_notice",
      source: {
        icon_url: "https://pic.tujia.com/upload/festatic/policy/ganfan.jpg",
        desc: "干饭人",
      },
      main_title: {
        title: "干饭人，干饭魂，干饭都是人上人，干饭不积极，做人有问题！",
        desc: "干饭人吃饭得用盆，今天吃，明天吃，干饭小伙最精神。",
      },
      card_image: {
        url: data.imageUrl,
        aspect_ratio: 1.8,
      },
      vertical_content_list: [
        {
          title: data.meiriyiju.title,
          desc: data.meiriyiju.desc,
        },
      ],
      jump_list: [
        {
          type: 1,
          url: "https://www.geekstool.com/eat.html",
          title: "不知道吃什么？点击查看。",
        },
        {
          url: data.imageUrl,
          title: "点击获取每日壁纸。",
        },
      ],
      card_action: {
        type: 1,
        url: data.imageUrl,
      },
    },
  };
  return axios.post(webhookUrl, params);
};

/**
 * 获取bing每日一图 数据结构如下
 * @returns Promise<{code: number, imgurl: string, width: number, 1080: number}>
 */
const getPic = () => {
  return axios.get("https://www.dmoe.cc/random.php?return=json");
};

/**
 * 获取每日一句
 * @returns Promise<{data: {from: string, hitokoto: string, from_who: string | null}}>
 */
const getOneJu = () => {
  return axios.get("https://v1.hitokoto.cn/");
};

// 干饭群通知任务
const task = async (webhookUrl = webhook) => {
  try {
    const pic = (await getPic()).data;
    const juzi = (await getOneJu()).data;
    await sendWebhook(
      {
        imageUrl: pic.imgurl,
        meiriyiju: {
          title: juzi.from_who || juzi.from,
          desc: juzi.hitokoto,
        },
      },
      webhookUrl
    );
  } catch (e) {
    console.error("干饭群通知任务失败了：", e);
  }
  setTimeout(async () => {
    await axios.post(webhookUrl, {
      msgtype: "text",
      text: {
        content: "到点啦！还不干饭去？",
        mentioned_list: ["@all"],
      },
    });
  }, 10000);
};

// 每天早上九点刷新任务。并且通知下次节假日信息
schedule.scheduleJob("0 0 12 * * *", function () {
  (async () => {
    // 获取今天的工作日状态
    await checkToady();
    if (isTodayWorkday) {
      // 获取最近的休息日
      const nextHoliday = await getNextHoliday();
      tongzhiwebhook.forEach(async (v) => {
        axios.post(v, {
          msgtype: "news",
          news: {
            articles: [
              {
                title: "想放假吗？",
                description: nextHoliday,
                url: "www.qq.com",
                picurl:
                  "https://pic.tujia.com/upload/festatic/policy/buxiangshangban.png",
              },
            ],
          },
        });
      });
    }
  })();
});

// 刷新今天假日状态
checkToady();

const job1 = schedule.scheduleJob("0 40 11 * * *", function () {
  if (isTodayWorkday) {
    task();
  }
});
const job2 = schedule.scheduleJob("0 40 17 * * *", function () {
  if (isTodayWorkday) {
    task();
  }
});

const job3 = schedule.scheduleJob("0 0 18 * * *", function () {
  if (isTodayWorkday) {
    task();
  }
});

/** 启动时候通知节假日信息 */
(async () => {
  // 获取今天的工作日状态
  await checkToady();
  if (isTodayWorkday) {
    // 获取最近的休息日
    const nextHoliday = await getNextHoliday();
    tongzhiwebhook.forEach(async (v) => {
      axios.post(v, {
        msgtype: "news",
        news: {
          articles: [
            {
              title: "想放假吗？",
              description: nextHoliday,
              url: "www.qq.com",
              picurl:
                "https://pic.tujia.com/upload/festatic/policy/buxiangshangban.png",
            },
          ],
        },
      });
    });
  }
})()
